package org.example.homework.controller;

import jakarta.servlet.http.HttpSession;
import org.example.homework.entity.CartItem;
import org.example.homework.entity.User;
import org.example.homework.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @PostMapping("/add")
    @ResponseBody
    public Map<String, Object> addToCart(@RequestBody Map<String, Object> request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.put("success", false);
            response.put("message", "请先登录");
            return response;
        }

        try {
            // 验证请求参数
            if (request.get("productId") == null || request.get("quantity") == null) {
                response.put("success", false);
                response.put("message", "商品ID和数量不能为空");
                return response;
            }

            Integer productId;
            Integer quantity;
            
            try {
                productId = Integer.parseInt(request.get("productId").toString());
                quantity = Integer.parseInt(request.get("quantity").toString());
            } catch (NumberFormatException e) {
                response.put("success", false);
                response.put("message", "商品ID和数量必须是有效的数字");
                return response;
            }

            // 验证数量是否为正数
            if (quantity <= 0) {
                response.put("success", false);
                response.put("message", "商品数量必须大于0");
                return response;
            }
            
            cartService.addToCart(user.getId(), productId, quantity);
            
            response.put("success", true);
            response.put("message", "成功加入购物车");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "加入购物车失败：" + e.getMessage());
        }
        
        return response;
    }

    @GetMapping
    public String viewCart(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }

        List<CartItem> cartItems = cartService.getCartItems(user.getId());
        System.out.println("cartItems: " + cartItems);
        model.addAttribute("cartItems", cartItems);
        return "cart";
    }

    @DeleteMapping("/{itemId}")
    @ResponseBody
    public Map<String, Object> removeFromCart(@PathVariable Integer itemId, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.put("success", false);
            response.put("message", "请先登录");
            return response;
        }

        try {
            cartService.removeFromCart(itemId, user.getId());
            response.put("success", true);
            response.put("message", "商品已从购物车移除");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }

    @PutMapping("/{itemId}")
    @ResponseBody
    public Map<String, Object> updateQuantity(@PathVariable Integer itemId, 
                                            @RequestBody Map<String, Object> request,
                                            HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.put("success", false);
            response.put("message", "请先登录");
            return response;
        }

        try {
            Integer quantity = Integer.parseInt(request.get("quantity").toString());
            cartService.updateQuantity(itemId, user.getId(), quantity);
            response.put("success", true);
            response.put("message", "数量已更新");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        
        return response;
    }
} 